<template>
	<div>
		<div class="bg" :style="{ 'background-image': 'url(' + getBackgroundImage(now.text) + ')' }">
			<goback title="农时预测"></goback>


			<div class="today_status">
				<div class="today_city_name">{{city}}</div>
				<div class="today_status_now">{{now.temperature}}°C </div>
				<div class="today_status_recommend">{{now.text}} {{now.wind_direction}}风</div>
			</div>
			<div class="card">
				<div class="card_title">今日农时</div>

				<div class="today_forecast_container">
					<div class="today_forecast_every" v-for="(item2,index) in severalHours">
						<div>{{item2.time}}:00</div>
						<img :src="require(`@/assets/weather/${item2.img}`)" v-if="item2.img != ''" />
						<div>{{item2.text}}</div>
						<div>{{item2.temperature}} °C</div>
					</div>
				</div>
			</div>


			<div class="card">
				<div class="card_title">未来预测</div>
				<div class="forecast_container">
					<div class="forecast_everycon" v-for="(item,index) in severalDays">
						<div>{{getRelativeDate(item.date)}}</div>
						<div>{{item.date.split('-').slice(1).join('-')}}</div>
						<img :src="require(`@/assets/weather/${item.img}`)" v-if="item.img != ''" />
						<div>{{item.text_day}}</div>
						<div>{{item.recommend}}</div>
						<div>{{item.high}}/{{item.low}}℃</div>
					</div>
				</div>
			</div>


			<div class="card">
				<div class="card_title">耕种指南</div>
				<div class="tip">
					{{ getFarmingAdvice(now.text) }}
				</div>
			</div>
			
			<div class="submit" @click="toVoice">
				<img class="animation1" :src="require('@/assets/weather/语音.png')" v-if="isSpeaking==false"/>
				<img class="animation1" :src="require('@/assets/weather/语音中.png')" v-else/>
			</div>
			
			<copyright></copyright>

		</div>
	</div>

</template>

<script>
	export default {
		name: "success",
		data() {
			return {
				city: [],
				severalHours: [],
				severalDays: [],
				now: [],
				farmingAdvice: {
					'晴': '今天天气晴朗，适宜出门劳作。',
					'多云': '多云天气，适宜进行农作物管理。',
					'阴': '阴天天气，适合进行田间作业。',
					'雨': '今天有雨，注意防水，避免在田间作业。'
				},
				audioElement: null,
				isSpeaking:false,
			};
		},
		mounted() {
			this.getData();
		},
		methods: {
			
			
			toVoice() {
				let context = `${this.city},目前是:${this.now.temperature}摄氏度,目前是${this.now.text},${this.now.wind_direction}风,宜${this.getFarmingAdvice(this.now.text)},1小时后预计是${this.severalHours[1].text},明日天气为:${this.severalDays[0].text_day},${this.severalDays[0].recommend},秸小宇为您播报完毕,感谢您的聆听~`;
				if (this.isSpeaking == false) {
					this.axios.get(`${this.IP}/text_to_voice`, {
							responseType: 'blob', // 告诉axios期望服务器响应的数据类型为blob  
							params: {
								text: context
							}
						}).then(response => {
							// 创建Blob对象  
							const blob = new Blob([response.data], {
								type: 'audio/mpeg'
							}); // 假设返回的是MP3格式的音频  
							// 创建一个指向该Blob对象的URL  
							const audioUrl = URL.createObjectURL(blob);
							// 创建一个audio元素并设置其src属性为上面创建的URL  
							this.audioElement = new Audio(audioUrl);
							// 播放音频  
							this.audioElement.play();
							// 当音频播放结束时，释放URL对象  
							this.audioElement.addEventListener('ended', () => {
								URL.revokeObjectURL(audioUrl);
								this.isSpeaking = !this.isSpeaking;
							});
							console.log('Audio playback started.');
						})
						.catch(error => {
							console.error('Error fetching audio:', error);
						});
				} else {
					this.audioElement.pause();
				}
				this.isSpeaking = !this.isSpeaking;
				this.$forceUpdate();
			},
			
			
			
			//计算日期
			getRelativeDate(date) {
				const targetDate = new Date(date);
				const currentDate = new Date();

				const diffTime = targetDate.getTime() - currentDate.getTime();
				const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

				if (diffDays === 1) {
					return '明天';
				} else if (diffDays === 2) {
					return '后天';
				} else {
					return this.getWeekday(targetDate.getDay());
				}
			},
			//计算周几
			getWeekday(day) {
				const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
				return weekdays[day];
			},
			//改变背景图
			getBackgroundImage(weather) {
				let backgroundImage = '';

				switch (weather) {
					case '晴':
						backgroundImage = require('@/assets/images/晴.jpg');
						break;
					case '多云':
						backgroundImage = require('@/assets/images/多云.jpg');
						break;
					case '阴':
						backgroundImage = require('@/assets/images/多云.jpg');
						break;
					case '雨':
						backgroundImage = require('@/assets/images/下雨.jpg');
						break;
					default:
						backgroundImage = require('@/assets/images/多云.jpg');
				}

				return backgroundImage;
			},
			//耕种指南
			getFarmingAdvice(weather) {
				return this.farmingAdvice[weather] || '天气变化无常，请根据实际情况进行农作业安排。';
			},
			getData() {
				this.axios.get(
					`https://api.seniverse.com/v3/weather/hourly.json?key=天气密钥&location=ip&language=zh-Hans&unit=c&start=0&hours=24`, {

					}).then(res => {
					this.severalHours = res.data.results[0].hourly.slice(0, 8);
					this.severalHours.forEach((e) => {
						e.time = e.time.slice(11, 13);
						if (e.text.includes('云')) {
							e.img = "云.png";
							e.recommend = "宜收耕";
						} else if (e.text.includes('雷')) {
							e.img = "雷.png";
							e.recommend = "忌收耕";
						} else if (e.text.includes('雪')) {
							e.img = "雪.png";
							e.recommend = "宜休息";
						} else if (e.text.includes('晴')) {
							e.img = "晴.png";
							e.recommend = "宜晾晒";
						} else if (e.text.includes('晴')) {
							e.img = "晴.png";
							e.recommend = "宜晾晒";
						} else if (e.text.includes('雨')) {
							e.img = "雨.png";
							e.recommend = "宜休息";
						} else if (e.text.includes('阴')) {
							e.img = "阴.png";
							e.recommend = "宜收耕";
						}
					})
					
					
					
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;

				this.axios.get(
					`https://api.seniverse.com/v3/weather/daily.json?key=天气密钥&location=ip&language=zh-Hans&unit=c&start=-1&days=9`, {

					}).then(res => {
					this.city = res.data.results[0].location.name
					this.severalDays = res.data.results[0].daily.slice(2, 9);


					this.severalDays.forEach((e) => {
						if (e.text_day.includes('云')) {
							e.img = "云.png";
							e.recommend = "宜收耕";
						} else if (e.text_day.includes('雷')) {
							e.img = "雷.png";
							e.recommend = "忌收耕";
						} else if (e.text_day.includes('雪')) {
							e.img = "雪.png";
							e.recommend = "宜休息";
						} else if (e.text_day.includes('晴')) {
							e.img = "晴.png";
							e.recommend = "宜晾晒";
						} else if (e.text_day.includes('晴')) {
							e.img = "晴.png";
							e.recommend = "宜晾晒";
						} else if (e.text_day.includes('雨')) {
							e.img = "雨.png";
							e.recommend = "宜休息";
						} else if (e.text_day.includes('阴')) {
							e.img = "阴.png";
							e.recommend = "宜收耕";
						}
					})



					console.log(this.severalDays);
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;



				this.axios.get(
					`https://api.seniverse.com/v3/weather/now.json?key=天气密钥&location=ip&language=zh-Hans&unit=c
`, {}).then(res => {
					this.now = res.data.results[0].now
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;


			}
		}
	}
</script>

<style scoped>
	
	.animation1{
		animation: 10s shake infinite alternate-reverse;
	}
	
	.submit img {  
	    position: fixed;  
	    bottom: 5vh;  
	    width: 96px;  
	    height: 96px;  
	    z-index: 11;  
	    left: 44vw;  
	    border: 1px solid #ebebeb;  
	    border-radius: 50%;  
	    /* 添加阴影来增强立体感 */  
	    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.8), 0 -2px 2px rgba(0, 0, 0, 0.2);  
	}
	
	
	
	.bg {
		width: 100%;
	}

	.card {
		background-color: rgba(255, 255, 255, 0.3) !important;
	}

	.today_status {
		margin: 100px auto;
		text-align: center;
		display: flex;
		flex-direction: column;
	}

	.today_status div {
		margin: 1vw;
	}

	.today_city_name {
		font-size: 46px;
	}

	.today_status_now {
		position: relative;
		font-size: 116px;
	}

	.today_status_now .temperature-unit {
		position: absolute;
		font-size: 50px;
	}

	.today_status_recommend {
		font-size: 32px;
	}

	.today_forecast_container {
		margin-top: 2vw;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
		text-align: center;
		overflow-x: auto;
		scroll-snap-type: x mandatory;
		/* 修改为 mandatory 以确保滚动总是对齐到元素 */
		scroll-behavior: smooth;
		/* 添加平滑滚动效果 */
	}

	.today_forecast_container::-webkit-scrollbar {
		display: none;
		/* 隐藏Chrome滚动条 */
	}

	.today_forecast_every {
		min-width: 23vw;
		overflow-x: scroll;
		scroll-snap-align: start;
		scroll-snap-stop: normal;
	}

	.today_forecast_every img {
		width: 42px;
	}

	.forecast_everycon img {
		width: 42px;
	}

	.forecast_container {
		margin: 6vw 0vw;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		scroll-snap-type: x mandatory;
		/* 修改为 mandatory 以确保滚动总是对齐到元素 */
		scroll-behavior: smooth;
		/* 添加平滑滚动效果 */
		overflow-x: auto;
	}

	.forecast_container::-webkit-scrollbar {
		display: none;
		/* 隐藏Chrome滚动条 */
	}

	.forecast_everycon {
		min-width: 23vw;
		scroll-snap-align: start;
		scroll-snap-stop: normal;
		text-align: center;
	}

	.tip {
		padding: 3vw;
		font-size: 28px;
		border-radius: 20px;
	}
</style>
